﻿/*修改历史：
 *
 *
 * 作者：mashanlin  m.sh.lin0328@163.com
 * 版本：V1.0
 * 完成日期：2012-8-28 22:25:00
 */
using System;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Collections.Generic;
using System.Collections;
using System.IO;

namespace MSL.Utility.Mail
{
    /// <summary>
    /// 发送邮件类
    /// </summary>
    public class MailHelper
    {
        #region 私有变量
        private String _smtpServer = "smtp.163.com";     //SMTP服务器,如：smtp.qq.com  smtp.163.com
        System.Text.Encoding _enCode = System.Text.Encoding.UTF8;                  //邮件编码
        private String[] _attachFiles = null;                      //附件
        private Int32 _prot = 25;                                          //端口号

        private String _sendFrom = string.Empty;           //发信人
        private String _sendFromCall = string.Empty;     //发信人称呼
        private String _pwd = string.Empty;                    //密码
        private String _subject = string.Empty;               //主题
        private String _content = string.Empty;              //内容
        private Hashtable _reciverHT = new Hashtable();     //收件人

        #endregion

        #region 属性
        /// <summary>
        /// SMTP服务器
        /// </summary>
        public string SmtpServer
        {
            get { return _smtpServer; }
            set { _smtpServer = value; }
        }
        /// <summary>
        /// 发信人
        /// </summary>
        public string SendFrom
        {
            get { return _sendFrom; }
            set { _sendFrom = value; }
        }
        /// <summary>
        /// 发信人称呼
        /// </summary>
        public string SendFromCall
        {
            get { return _sendFromCall; }
            set { _sendFromCall = value; }
        }
        /// <summary>
        /// 密码
        /// </summary>
        public string Pwd
        {
            get { return _pwd; }
            set { _pwd = value; }
        }
        /// <summary>
        /// 附件
        /// </summary>
        public string[] AttachFiles
        {
            get { return _attachFiles; }
            set { _attachFiles = value; }
        }
        /// <summary>
        /// 主题
        /// </summary>
        public string Subject
        {
            get { return _subject; }
            set { _subject = value; }
        }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content
        {
            get { return _content; }
            set { _content = value; }
        }
        /// <summary>
        /// 收件人
        /// </summary>
        public Hashtable ReciverHT
        {
            get { return _reciverHT; }
            set { _reciverHT = value; }
        }
        /// <summary>
        /// 邮件编码
        /// </summary>
        public System.Text.Encoding EnCode
        {
            get { return _enCode; }
            set { _enCode = value; }
        }
        /// <summary>
        /// 端口号
        /// </summary>
        public Int32 Prot
        {
            get { return _prot; }
            set { _prot = value; }
        }

        #endregion

        #region 构造函数
        public MailHelper()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendFrom">发件人</param>
        /// <param name="reciveHT">收件人</param>
        /// <param name="pwd">密码</param>
        public MailHelper(string sendFrom, Hashtable reciveHT, string pwd)
        {
            this.SendFrom = sendFrom;
            this._reciverHT = reciveHT;
            this._pwd = pwd;
        }
        #endregion

        /// <summary>
        /// 发送邮件
        /// </summary>
        public bool SendEmail()
        {
            if (SendFrom == "" || Pwd == "" || ReciverHT.Count == 0 || Subject == "" || Content == "")
            {
                return false;
            }

            #region 设置邮件信息
            // 发送邮件对象
            MailMessage Message = new MailMessage();

            // 发件人地址
            if (SendFromCall == "")
            {
                Message.From = new MailAddress(SendFrom);
            }
            else
            {
                Message.From = new MailAddress(SendFrom, SendFromCall, EnCode);
            }

            // 收件人
            if (ReciverHT.Count > 0)
            {
                foreach (DictionaryEntry dictEntry in ReciverHT)
                {
                    Message.To.Add(new MailAddress(dictEntry.Value.ToString(), dictEntry.Key.ToString(), EnCode));//收信人地址
                }
            }
            // 邮件的优先级
            Message.Priority = MailPriority.High;
            // 邮件的主题
            Message.Subject = Subject;
            // 邮件的内容
            Message.Body = Content;
            //邮件正文格式
            Message.IsBodyHtml = true;
            // 设置邮件内容编码方式
            Message.BodyEncoding = EnCode;
            #endregion

            #region 获取所有邮件附件
            if (AttachFiles != null && AttachFiles.Length > 0)
            {
                for (int n = 0; n < AttachFiles.Length; n++)
                {
                    if (AttachFiles[n] != "" && File.Exists(AttachFiles[n]))
                    {
                        //附件对象
                        Attachment attData = new Attachment(AttachFiles[n], MediaTypeNames.Application.Octet);
                        //附件资料
                        /*
                        ContentDisposition disposition = attData.ContentDisposition;
                        disposition.CreationDate = System.IO.File.GetCreationTime(AttachFiles[n]);
                        disposition.ModificationDate = System.IO.File.GetLastWriteTime(AttachFiles[n]);
                        disposition.ReadDate = System.IO.File.GetLastAccessTime(AttachFiles[n]);
                         */
                        //加入邮件附件
                        Message.Attachments.Add(attData);
                    }
                }
            }
            #endregion

            #region 设置发送邮件的smtp服务器信息

            // 指定SMTP服务器smtp：25，接收邮件服务器pop:110
            SmtpClient Client = new SmtpClient(SmtpServer);
            //发送端口
            Client.Port = Prot;
            //Client.EnableSsl=false;
            //是否发送身份验证
            Client.UseDefaultCredentials = true;
            //指定处理邮件的方式，此处为通过网络发送到smtp服务器
            Client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //验证发件人身份，用户名kaixiyeetop，密码******
            if (Client.UseDefaultCredentials)
            {
                Client.Credentials = new System.Net.NetworkCredential(SendFrom, Pwd);
            }
            #endregion

            #region 发送邮件
            try
            {
                //发送邮件
                Client.Send(Message);
                return true;
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
                    {
                        System.Threading.Thread.Sleep(5000);
                        Client.Send(Message);
                    }
                }
                return false;
            }
            finally
            {
                foreach (Attachment item in Message.Attachments)
                {
                    item.Dispose();   //一定要释放该对象,否则无法删除附件
                }
                Client.Dispose();
            }
            #endregion
        }
    }
}